//! axios基础封装
import axios from "axios";
import 'element-plus/theme-chalk/el-message.css'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cartStore'
import router from '@/router'
//! 因为vue3不能在setup外使用useRouter
// 所以这里是从路由里面引入
const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 5000,
})
//!axios设置请求拦截器
httpInstance.interceptors.request.use(config => {
    //!1.从pinia获取token数据
    //！因为好多接口都得有token才可以鉴权
    const token = useUserStore().userInfo.token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    //!2.按照后端要求拼接
    return config
}, err => {
    console.log(err)
})

//!axios设置响应拦截器
httpInstance.interceptors.response.use(response => {
    return response.data //拦截处理响应结果，直接返回需要的数据S
}, err => {
    ElMessage({
        type: 'error',
        message: err.response.data.message
    })
    //!401token失效处理
    //!1.清除本地用户数据
    //!2.跳转登录页面
    if (err.response.status == 401) {
        //!清除用户信息
        useUserStore().clearUserInfo()
        const cartStore = useCartStore()
        //!清除购物车
        cartStore.clearCart()
        router.replace({ path: '/login' })
    }
})

export default httpInstance